package com.xzc.shopping.config;

import com.google.gson.Gson;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.nio.charset.StandardCharsets;

@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);

        // 使用 Gson 序列化器
        GsonRedisSerializer gsonSerializer = new GsonRedisSerializer();

        // Key 用 String 序列化
        template.setKeySerializer(new StringRedisSerializer());
        template.setHashKeySerializer(new StringRedisSerializer());

        // Value 用 Gson 序列化
        template.setValueSerializer(gsonSerializer);
        template.setHashValueSerializer(gsonSerializer);

        template.afterPropertiesSet();
        return template;
    }

    // 自定义 Gson 序列化器
    public static class GsonRedisSerializer implements RedisSerializer<Object> {
        private final Gson gson = new Gson();

        @Override
        public byte[] serialize(Object o) throws SerializationException {
            return gson.toJson(o).getBytes(StandardCharsets.UTF_8);
        }

        @Override
        public Object deserialize(byte[] bytes) throws SerializationException {
            if (bytes == null || bytes.length == 0) {
                return null;
            }
            return gson.fromJson(new String(bytes, StandardCharsets.UTF_8), Object.class);
        }
    }
}